package com.wisewin.pose.util.wechat;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wisewin.pose.config.dto.ResultDTO;
import com.wisewin.pose.config.dto.ResultDTOBuilder;
import com.wisewin.pose.entity.db.UserDO;
import com.wisewin.pose.util.JedisUtil;
import com.wisewin.pose.util.JsonUtil;
import com.wisewin.pose.util.wechat.xcx.entity.WechatOffice;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WechatOfficeUtil {
    final static Logger log = LoggerFactory.getLogger(WechatOfficeUtil.class);

    private static String appId;
    private static String appSecret;

    public WechatOfficeUtil(String appId, String appSecret) {
        this.appId = appId;
        this.appSecret = appSecret;
    }

    public static ResultDTO getOpenId(String code) {
        if (StringUtils.isEmpty(code)) {
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        try {
            // 获取accessToken
            WechatOffice wechatOffice = getAccessToken(code);
            log.info("--wechatOffice-" + wechatOffice);
            if (wechatOffice == null) {
                return ResultDTOBuilder.failure("1", "获取access_token失败", null);
            }
            String openId = wechatOffice.getOpenid();
            log.info("openid " + openId);
            if (StringUtils.isEmpty(openId)) {
                return ResultDTOBuilder.failure("1", "获取用户信息失败", null);
            }
            UserDO userDo = new UserDO();
            userDo.setOpenid(openId);
            return ResultDTOBuilder.success(userDo);
        } catch (Exception e) {
            return ResultDTOBuilder.failure("1", "获取用户信息失败", null);
        }
    }

    public static ResultDTO getUserInfo(String code) {
        if (StringUtils.isEmpty(code)) {
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        try {
            // 获取accessToken
            WechatOffice wechatOffice = getAccessToken(code);
            if (wechatOffice == null) {
                return ResultDTOBuilder.failure("1", "获取access_token失败", null);
            }
            String accessToken = wechatOffice.getAccess_token();
            String openId = wechatOffice.getOpenid();
            // 请求获取用户信息接口
            String userinfo_url = String.format(
                    "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&access_token=%s&openid=%s", accessToken, openId,
                    code);
            JSONObject result = JSON.parseObject(HttpUtil.get(userinfo_url));
            log.info("==========获取用户信息：" + result.toJSONString() + "============");
            if (!result.containsKey("openid")) {
                return ResultDTOBuilder.failure("1", "获取用户信息失败", null);
            }
            UserDO userDo = JsonUtil.stringToObj(result.toJSONString(), UserDO.class);
            return ResultDTOBuilder.success(userDo);
        } catch (Exception e) {
            return ResultDTOBuilder.failure("1", "获取用户信息失败", null);
        }
    }

    // 获取accessToken
    public static WechatOffice getAccessToken(String code) {
        // 获取token
        String token_url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                appId, appSecret, code);
        JSONObject result = JSON.parseObject(HttpUtil.get(token_url));
        log.info("============获取token结果" + result.toJSONString() + "============");
        if (!result.containsKey("access_token")) {
            return null;
        }
        WechatOffice wechatOffice = JsonUtil.stringToObj(result.toJSONString(), WechatOffice.class);
        return wechatOffice;
    }

    // 获取accessToken
    public static String getToken() {
        // 从redis中获取accessToken
        String token = JedisUtil.get("token" + appId);
        if (token == null) {
            // 获取token
            String token_url = String.format(
                    "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId,
                    appSecret);
            JSONObject result = JSON.parseObject(HttpUtil.get(token_url));
            if (result == null) {
                return null;
            }
            token = result.getString("token");
            // 过期时间
            Long expiresIn = result.getLong("expires_in");
            // 存入redis
            JedisUtil.setEx("token" + appId, token, expiresIn);
        }
        return token;
    }
}
